<?php


namespace app\api\controller;


use app\common\model\AdminModel;
use GatewayWorker\BusinessWorker;
use GatewayWorker\Lib\Gateway;
use Workerman\Worker;
use app\common\model\BusOrderModel;
use app\common\model\GoodslistModel;
use app\common\model\OrderitemMoel;
use app\common\model\OrderMoel;
use think\Request;

class Usershopcart extends Base
{
    ///用户购物车
    public function insert(Request $request){
        $param = $request->param();
        ///根据userid+goods_id可以唯一确定一个商品是否在购物车
        $goods_id = $request->param('goods_id');
        $userid = $request->param('userid');
        $count = $request->param('count');
        $orderitem = new OrderitemMoel();
        $exists = $orderitem->where('status', 0)->where('goods_id', $goods_id)
            ->where('userid',$userid)->find();
        ////是否已经加入购物车，若已经加入购物车，则为更新操作,否则为插入操作
        ///         此后操作时，都需要先判断

        ///获取该物品的最大购买数量信息
        $goods = new GoodslistModel();
        $goodsinfo = $goods->where('id', $goods_id)->find();
        $maxcount = $goodsinfo['count'];
//        echo $maxcount;
        $singleprice = $goodsinfo['price'];
//        echo $exists;
        if($exists){
            if($maxcount<$count){
                return json(['code'=>0, 'msg'=>'添加失败,购买数量超过允许购买的最大值'.$maxcount]);
            }
            else{
                /// 更新操作
                $param['price'] = $count * $singleprice;
                $orderitem->save($param, ['id'=>$exists['id']]);
                return json(['code'=>1, 'msg'=>'更新购物车商品数量成功']);
            }
        }
        else{
            if($maxcount<$count){
                return json(['code'=>0, 'msg'=>'添加失败,购买数量超过允许购买的最大值'.$maxcount]);
            }
            else{
                ///插入操作
                $param['price'] = $count * $singleprice;
                $orderitem->save($param);
                return json(['code'=>1, 'msg'=>'购物车添加物品成功']);
            }
        }
    }
    public function update(Request $request){
        $param = $request->param();
        ///根据userid+goods_id可以唯一确定一个商品是否在购物车
        $goods_id = $request->param('goods_id');
        $userid = $request->param('userid');
        $count = $request->param('count');
        $orderitem = new OrderitemMoel();
        ///查看该条数据库信息的id
        $exists = $orderitem->where('userid', $userid)->where('goods_id', $goods_id)->where('status',0)
            ->find();
        ///获取该物品的最大购买数量信息
        $goods = new GoodslistModel();
        $goodsinfo = $goods->where('id', $goods_id)->find();
        $maxcount = $goodsinfo['count'];
        $singleprice = $goodsinfo['price'];
        if($count <= $maxcount){
            $param['price'] = $count * $singleprice;
            $i=$orderitem->save($param, ['id'=>$exists['id']]);
            return json(['code'=>1, 'msg'=>'数据库更新数据成功','$i'=>$param['price'] ]);
        }
        else{
            return json(['code'=>0, 'msg'=>'超出可选购数量'.$maxcount]);
        }
    }

    public function query(Request $request){
        $userid = $request->param('userid');
        $orderitem = new OrderitemMoel();
        $key = $request->param('key');
        ///判断是否有关键字,如果有关键字，先进行一次筛选
        if(isset($key) && !empty($key)){
            $orderitem = $orderitem->where("goods_name", 'like', '%'.$key.'%');     /// 模糊搜索
        }
        $exists = $orderitem->where('status', 0)
            ->where('userid', $userid)->select();
        return json(['code'=>'1', 'msg'=>'查询成功', 'data'=>$exists]);

    }
    public function del(Request $request){
        $param = $request->param();
        ///根据userid+goods_id可以唯一确定一个商品是否在购物车
        $goods_id = $request->param('goods_id');
        $userid = $request->param('userid');
        $orderitem = new OrderitemMoel();
        $exists = $orderitem->where('status', 0)->where('goods_id', $goods_id)
            ->where('userid',$userid)->find();
        if($exists){
            $orderitem->where('status', 0)->where('goods_id', $goods_id)
                ->where('userid',$userid)->delete();
            return json(['code'=>'1', 'msg'=>'删除成功']);
        }
        else{
            return json(['code'=>'0', 'msg'=>'购物车中不存在该物品']);
        }
    }
    public function delall(Request $request){
        $param = $request->param();
        ///根据userid+goods_id可以唯一确定一个商品是否在购物车
        $goods_id = $request->param('goods_id');
        $userid = $request->param('userid');
        $orderitem = new OrderitemMoel();

        $orderitem->where('status', 0)
            ->where('userid',$userid)->where('goods_id', 'in', $goods_id)->delete();
        return json(['code'=>'1', 'msg'=>'删除成功']);
    }

    /**
     * @throws \Exception
     */
    public function order(Request $request){
        $order = new OrderMoel();
        $busorder = new BusOrderModel();
        $goodslist = new GoodslistModel();

        $orderinfo = array();
        $orderinfo['username'] = $request->param('username');
        $orderinfo['userid']  = $request->param('userid');
        $orderinfo['totalAmout']  = $request->param('totalAmout');
        $orderinfo['totalNum'] = $request->param('totalNum');
        $orderinfo['create_time']  = $request->param('create_time');

        $goods_id = $request->param('goods_id'); ///数组形式
        if(empty($goods_id))
            return json(['code'=>'0','msg'=>'您未选中任何商品']);

        $order->save($orderinfo);

        $param = $request->param();

        $userid = $request->param('userid');
        $orderitem = new OrderitemMoel();

        $user=new AdminModel();
        $tel=$user->where('id',$userid)->find();
        if(strlen($tel['telephone'])!=11)
        {
            return json(['code' => 0, 'msg' => '未提供有效联系方式无法下单,请在个人信息中心完善信息']);
        }
        else if($tel['addr']=='未设置地址')
        {
            return json(['code'=>0, 'msg'=>'未提供地址无法下单,请在个人信息中心完善信息']);
        }
        $orderitem->where('status', 0)
            ->where('userid',$userid)->where('goods_id', 'in', $goods_id)
            ->update(['status'=>1, 'orderid'=>$order['id']]);

        $res=$orderitem->where('orderid',$order['id'])->field('shop_id,SUM(count*price) totalAmout,count(id) totalNum')->group('shop_id')->select();
        foreach($res as $key => $value)
        {
            $busod=array();
            $busod['userid']=$order['userid'];
            $busod['orderid']=$order['id'];
            $busod['busid']=$value['shop_id'];
            $busod['totalAmout']=$value['totalAmout'];
            $busod['totalNum']=$value['totalNum'];
            $busod['create_time']=time();
            $busod['address']=$tel['addr'];
            $busorder->insert($busod);
            //echo $busorder->getLastSql();
            $orderitem->where('orderid',$order['id'])->where('shop_id',$busod['busid'])->update(['busorderid' => $busorder->getLastInsID()]);
        }
        return json(['code'=>'1', 'msg'=>'生成订单成功']);
    }
    public function showorder(Request $request){
        $order = new OrderMoel();
        $userid = $request->param('userid');
        $kind = $request->param('kind');
        $search_key = $request->param('key');
        if($kind==0 && $search_key!=""){
            $order=$order->where("id", 'like', '%'.$search_key.'%');     /// 按订单模糊搜索
        }
        $orderinfo = $order->where('userid', $userid)->order(['create_time'=>'desc'])->limit(30)->select();
        $array = array();
        foreach ( $orderinfo as $key=>$value){
            $array1 = [];
            $array1['totalAmout'] = $value['totalAmout'];
            $array1['totalNum'] = $value['totalNum'];
            $array1['create_time'] = $value['create_time'];
            $array1['id'] = $value['id'];
            $temparray = array();
            ////添加商家对应的物品
            $orderitem = new OrderitemMoel();

            if($kind==1 && $search_key!=""){
                $orderitem=$orderitem->where("goods_name", 'like', '%'.$search_key.'%');     /// 按菜品模糊搜索
            }


            $orderiteminfo = $orderitem->where('orderid', $array1['id'])
            ->where('status', 1)->select();
//            echo $orderitem->getLastSql();
            $busorder=new BusOrderModel();

            foreach ($orderiteminfo as $key =>$inner_value){
                $array2 = [];
                $array2['shop_id'] = $inner_value['shop_id'];
                $array2['shop_name'] = $inner_value['shop_name'];
                $array2['goods_id'] = $inner_value['goods_id'];
                $array2['goods_name'] = $inner_value['goods_name'];
                $array2['goods_img'] = $inner_value['goods_img'];
                $array2['price'] = $inner_value['price'];
                $array2['count'] = $inner_value['count'];
                $state=$busorder->where('id',$inner_value['busorderid'])->find();
                $array2['state']=$state['state'];
                $score_state=$orderitem->where('goods_id',$array2['goods_id'])
                    ->where('shop_id',$array2['shop_id'])->where('orderid',$array1['id'])->find();
                $array2['score_state']=$score_state['score_state'];
                $array2['score']=$inner_value['score'];


                $temparray[] = $array2;
            }
            $array1['goods'] = $temparray;
            if($kind==0 || !$orderiteminfo->isEmpty())
                $array[] = $array1;
        }
        return json(['code'=>1,'msg'=>'查询成功','order_list'=>$array]);
    }


}